
package com.kweative.model.relation;

import com.kweative.model.Index;
import com.kweative.model.Table;
import com.kweative.model.data.Row;
import com.kweative.model.exception.ColumnAlreadyExistsException;
import com.kweative.model.exception.IndexNotFoundException;
import com.kweative.model.column.Column;
import com.kweative.model.column.ColumnInteger;
import com.kweative.model.query.Select;
import com.kweative.model.query.SetterStatement;
import com.kweative.model.query.WhereStatement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author henrik
 */
public class RelationOne2One<P extends Table,C extends Table> extends Relation<P, C> implements ISimpleRelation<P,C> {
    protected Column childColumn;
    protected Column parentColumn;
    public RelationOne2One(P child) {
        super(child);
    }

    @Override
    protected void makeStructure() {
        String indexName = String.format("%s_o2o",getParent().getName());
        String colName = String.format("%s_key",indexName);
        parentColumn = getParent().__primary;

        Index findex = getChild().addIndex(new Index(indexName, Index.Type.UNIQUE));
        try {
            childColumn = getChild().addColumn(new ColumnInteger(colName), findex);
        } catch (IndexNotFoundException ex) {
            Logger.getLogger(RelationOne2Many.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ColumnAlreadyExistsException ex) {
            Logger.getLogger(RelationOne2Many.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public WhereStatement<Select,P> join(WhereStatement<Select,P> where) {
        if (where.getTable().equals(getParent()))
            where.join(getChild()).where(childColumn).isEqual(parentColumn).columns();
        else
            where.join(getParent()).where(parentColumn).isEqual(childColumn).columns();
        
        return where;
    }

    public Column getChildColumn() {
        return childColumn;
    }

    public Column getParentColumn() {
        return parentColumn;
    }
    

    public void set(SetterStatement stmt, Row<P> row) {
        if (stmt.getTable().equals(getChild()))
            stmt.set(childColumn,row.__primary);
    }

    public void add(SetterStatement stmt, Row<C> row) {
        if (stmt.getTable().equals(getChild()))
            stmt.set(childColumn,row.__primary);
    }
}
